package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private RechargeInfoMapper rechargeInfoMapper;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;

    @Override
    public IPage<UserAccountDetail> findUserConsumePage(Page<UserAccountDetail> detailPage, Long userId) {
        //  select * from user_account_detail where user_id = ? and trade_type = ? limit 0,10
        return userAccountDetailMapper.selectPage(detailPage, new LambdaQueryWrapper<UserAccountDetail>().eq(UserAccountDetail::getUserId, userId).eq(UserAccountDetail::getTradeType, SystemConstant.ACCOUNT_TRADE_TYPE_MINUS));
    }

    @Override
    public IPage<UserAccountDetail> findUserRechargePage(Page<UserAccountDetail> detailPage, Long userId) {
        //  select * from user_account_detail where user_id = ? and trade_type = ? limit 0,10
        return userAccountDetailMapper.selectPage(detailPage, new LambdaQueryWrapper<UserAccountDetail>().eq(UserAccountDetail::getUserId, userId).eq(UserAccountDetail::getTradeType, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rechargePaySuccess(String orderNo) {
        //	查询对象
        RechargeInfo rechargeInfo = getRechargeInfoByOrderNo(orderNo);
        //	判断
        if (null != rechargeInfo && SystemConstant.ORDER_STATUS_PAID.equals(rechargeInfo.getRechargeStatus())) {
            return;
        }
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
        //	更新数据
        rechargeInfoMapper.updateById(rechargeInfo);
        //  先更新账户余额
        userAccountMapper.updateAmount(rechargeInfo.getUserId(), rechargeInfo.getRechargeAmount());
        //  添加账户明细
        this.addUserAccountDetail(rechargeInfo.getUserId(), "充值成功", SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, rechargeInfo.getRechargeAmount(), orderNo);
    }

    @Override
    public RechargeInfo getRechargeInfoByOrderNo(String orderNo) {
        //  根据订单编号查询充值对象
        RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));
        return rechargeInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int checkAndDeduct(AccountDeductVo accountDeductVo) {
        //	本质就是执行sql语句：
        int result = userAccountMapper.checkAndDeduct(accountDeductVo.getUserId(), accountDeductVo.getAmount());
        if (result == 0) {
            throw new GuiguException(222, "账户余额不足");
        }
        //	记录当前资金变化日志.
        this.addUserAccountDetail(accountDeductVo.getUserId(), "检查与扣减金额", SystemConstant.ACCOUNT_TRADE_TYPE_MINUS, accountDeductVo.getAmount(), accountDeductVo.getOrderNo());
        //	返回结果
        return result;
    }

    public void addUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
        //	创建对象
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        userAccountDetail.setUserId(userId);
        userAccountDetail.setTitle(title);
        userAccountDetail.setTradeType(tradeType);
        userAccountDetail.setAmount(amount);
        userAccountDetail.setOrderNo(orderNo);
        //	保存数据
        userAccountDetailMapper.insert(userAccountDetail);
    }

    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        //	select available_amount from user_account where user_id = ?
        return userAccountMapper.selectOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, userId).select(UserAccount::getAvailableAmount)).getAvailableAmount();
    }

    @Override
    public void initUserAccount(Long userId) {
        //	创建对象
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccount.setTotalAmount(new BigDecimal("1000"));
        userAccount.setAvailableAmount(new BigDecimal("1000"));
        userAccount.setTotalIncomeAmount(new BigDecimal("1000"));
        //	初始化金额；
        userAccountMapper.insert(userAccount);
    }
}
